<template>
  <div class="services-form">
    <el-card shadow="never">
      <template #header>
        <div class="page-header">
          <h2>{{ isEdit ? '编辑服务' : '添加服务' }}</h2>
          <el-button @click="$router.back()">返回</el-button>
        </div>
      </template>

      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="120px"
        class="form-container"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="服务名称" prop="serviceName">
              <el-input v-model="form.serviceName" placeholder="请输入服务名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="服务描述" prop="serviceDescription">
              <el-input
                v-model="form.serviceDescription"
                type="textarea"
                :rows="3"
                placeholder="请输入服务描述"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="标准时长(分钟)" prop="durationMinutes">
              <el-input-number
                v-model="form.durationMinutes"
                :min="0"
                placeholder="请输入标准时长"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="价格" prop="servicePrice">
              <el-input-number
                v-model="form.servicePrice"
                :min="0"
                :precision="2"
                placeholder="请输入价格"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="适用宠物类型" prop="applicablePetType">
                <el-select v-model="form.applicablePetType" placeholder="请选择适用宠物类型" style="width: 200px;">
                  <el-option label="猫" value="猫" />
                  <el-option label="狗" value="狗" />
                  <el-option label="通用" value="通用" />
                </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item>
          <el-button type="primary" @click="handleSubmit" :loading="loading">
            {{ isEdit ? '更新' : '保存' }}
          </el-button>
          <el-button @click="handleCancel">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { servicesApi } from '@/api'
import type { Services } from '@/types'

const router = useRouter()
const route = useRoute()

const formRef = ref<FormInstance>()
const loading = ref(false)

// 判断是否为编辑模式
const isEdit = computed(() => {
  return route.params.id !== undefined
})

// 表单数据
const form = reactive<Services>({
  serviceId: undefined,
  serviceName: '',
  serviceDescription: '',
  applicablePetType: '',
  durationMinutes: 60,
  servicePrice: 0
})

// 表单验证规则
const rules: FormRules = {
  serviceName: [
    { required: true, message: '请输入服务名称', trigger: 'blur' }
  ],
  serviceDescription: [
    { required: true, message: '请输入服务描述', trigger: 'blur' }
  ],
  applicablePetType: [
    { required: true, message: '请输入适用宠物类型', trigger: 'blur' }
  ],
  durationMinutes: [
    { required: true, message: '请输入标准时长', trigger: 'blur' }
  ],
  servicePrice: [
    { required: true, message: '请输入价格', trigger: 'blur' }
  ]
}

// 获取服务详情
const fetchServiceDetail = async (id: number) => {
  try {
    const response = await servicesApi.getById(id)
    if (response.code === 200) {
      const data = response.data
      Object.assign(form, {
        serviceId: data.serviceId,
        serviceName: data.serviceName,
        serviceDescription: data.serviceDescription,
        applicablePetType: data.applicablePetType || data.applicablepettype || '', // 兼容两种字段名
        durationMinutes: data.durationMinutes,
        servicePrice: data.servicePrice
      })
    } else {
      ElMessage.error(response.message || '获取服务详情失败')
    }
  } catch (error) {
    console.error('获取服务详情失败:', error)
    ElMessage.error('获取服务详情失败')
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    loading.value = true
    
    // 处理宠物类型数据
    const submitData = {
      ...form,
      // 将applicablePetType转换为数组格式
      applicablePetTypes: Array.isArray(form.applicablePetType) 
        ? form.applicablePetType 
        : [form.applicablePetType]
    }

    const apiCall = isEdit.value
      ? servicesApi.update(submitData)
      : servicesApi.add(submitData)
      
    const response = await apiCall
    
    if (response.code === 200) {
      ElMessage.success(isEdit.value ? '更新成功' : '添加成功')
      router.push('/system/services')
    } else {
      ElMessage.error(response.message || '操作失败')
    }
  } catch (error) {
    console.error('提交表单失败:', error)
  } finally {
    loading.value = false
  }
}

// 取消操作
const handleCancel = () => {
  router.push('/system/services')
}

onMounted(() => {
  if (isEdit.value) {
    const serviceId = Number(route.params.id)
    if (serviceId) {
      fetchServiceDetail(serviceId)
    }
  }
})
</script>

<style scoped>
.services-form {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.page-header h2 {
  margin: 0;
  color: #303133;
}

.form-container {
  max-width: 800px;
  margin: 0 auto;
}
</style> 